﻿<template>
  <a-modal
    :title="title"
    width="70%"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @cancel="
      () => {
        this.visible = false
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
        <a-form-model-item label="申请单号" prop="Id">
          <a-input v-model="entity.Id" disabled autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item label="申请日期" prop="CreateTime">
          <a-input v-model="entity.CreateTime" disabled autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item label="服务请求部门" prop="RequestDepartmentId">
          <a-tree-select
            v-model="entity.RequestDepartmentId"
            allowClear
            :treeData="DepartmentRequestIdTreeData"
            placeholder="请选择服务请求部门"
            @change="onTreeRequestDepartmentChange"
            treeDefaultExpandAll
            multiple
          ></a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="服务请求人员" prop="RequestUsers">
          <a-table
            ref="RequestUsersTable"
            :columns="RequestUsersColumns"
            :rowKey="(row) => row.UserId"
            :dataSource="entity.RequestUsers"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: RequestUsersSelectedRowKeys, onChange: onRequestUsersSelectChange }"
            :bordered="true"
            size="small"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleRequestUsersEdit(record)" v-if="entity.State == 1">编辑</a>
                <a-divider type="vertical" v-if="entity.State == 1" />
                <a @click="handleRequestUsersEdit(record)" v-if="entity.State == 3">编辑</a>
                <a-divider type="vertical" v-if="entity.State == 3" />
                <a @click="handleRequestUsersDelete([record.Id], record.UserId)" v-if="entity.State == 0">删除</a>
              </template>
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="提供服务部门" prop="DeliveryDepartmentId">
          <a-tree-select
            v-model="entity.DeliveryDepartmentId"
            allowClear
            :treeData="DepartmentDeliveryIdTreeData"
            placeholder="请选择提供服务部门"
            @change="onTreeDeliveryDepartmentChange"
            treeDefaultExpandAll
            multiple
          ></a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="提供服务人员" prop="DeliveryUsers">
          <a-table
            ref="DeliveryUsersTable"
            :columns="DeliveryUsersColumns"
            :rowKey="(row) => row.UserId"
            :dataSource="entity.DeliveryUsers"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: DeliveryUsersSelectedRowKeys, onChange: onDeliveryUsersSelectChange }"
            :bordered="true"
            size="small"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleDeliveryUsersEdit(record)" v-if="entity.State == 0">编辑</a>
                <a-divider type="vertical" v-if="entity.State == 0" />
                <a @click="handleDeliveryUsersDelete([record.Id], record.UserId)" v-if="entity.State == 0">删除</a>
              </template>
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="金额" prop="Amount">
          <a-input v-model="entity.Amount" disabled autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item label="科目名称" prop="AccountId">
          <a-select v-model="entity.AccountId" allowClear placeholder="请选择科目" :disabled="isAccount">
            <a-select-option v-for="item in AccountIdData" :key="item.Id">{{ item.Name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="服务项目" prop="ServiceItems">
          <div class="table-operator" v-if="entity.State == 0">
            <a-button type="primary" style="margin-right: 8px" icon="plus" @click="hanldleServiceItemsAdd()"
              >新建</a-button
            >
            <!-- <a-button
              style="margin-right: 8px"
              type="primary"
              icon="minus"
              @click="handleServiceItemsDelete(ServiceItemsSelectedRowKeys)"
              :disabled="!hasServiceItemsSelected()"
              :loading="loading"
              >删除</a-button
            >
            <a-button type="primary" style="margin-right: 8px" icon="redo" @click="serviceIetmsRefresh()"
              >刷新</a-button
            > -->
          </div>
          <a-table
            ref="ServiceItemsTable"
            :columns="ServiceItemsColumns"
            :rowKey="(row) => row.ServiceItemId"
            :dataSource="entity.ServiceItems"
            :pagination="pagination"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: ServiceItemsSelectedRowKeys, onChange: onServiceItemsSelectChange }"
            :bordered="true"
            size="small"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="showDetail(record.Name, record.Content)">查看项目详情</a>
                <a-divider type="vertical" />
                <a @click="handleQtyEdit(record)" v-if="entity.State == 0">编辑</a>
                <a-divider type="vertical" v-if="entity.State == 0" />
                <a @click="handleServiceItemsDelete([record.ServiceItemId])" v-if="entity.State == 0">删除</a>
              </template>
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="服务请求清单(备注)" prop="Remark">
          <a-input v-model="entity.Remark" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item label="隐藏列" prop="visible" hidden>
          <a-input ref="visible" v-model="entity.Visible" autocomplete="off" />
        </a-form-model-item>
        <!-- <a-form-model-item label="审批人" prop="Approver">
          <a-select v-model="entity.Approver" allowClear placeholder="请选审批人">
            <a-select-option v-for="item in DepartmentHead" :key="item.UserId">{{ item.UserName }}</a-select-option>
          </a-select>
        </a-form-model-item> -->
      </a-form-model>
      <request-user ref="requestUser" :parentObj="this"></request-user>
      <delivery-user ref="deliveryUser" :parentObj="this"></delivery-user>
      <service-item ref="serviceItem" :parentObj="this"></service-item>
      <show-detail ref="showDetail" :parentObj="this"></show-detail>
      <edit-service-item ref="editServiceItem" :parentObj="this" />
    </a-spin>
  </a-modal>
</template>

<script>
const RequestUsersColumns = [
  { title: '姓名', dataIndex: 'UserName', width: '10%' },
  { title: '金额', dataIndex: 'Amount', width: '10%' },
  { title: '评分', dataIndex: 'Score', width: '10%' },
  { title: '评价描述', dataIndex: 'Describe', width: '20%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } },
]

const DeliveryUsersColumns = [
  { title: '姓名', dataIndex: 'UserName', width: '10%' },
  { title: '金额', dataIndex: 'Amount', width: '10%' },
  // { title: '是否负责人', dataIndex: 'Principal', width: '15%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } },
]

const ServiceItemsColumns = [
  { title: '编码', dataIndex: 'Number', width: '10%' },
  { title: '服务项目', dataIndex: 'Name', width: '10%' },
  //{ title: '详细内容', dataIndex: 'Content', width: '30%' },
  { title: '数量', dataIndex: 'Quantity', width: '10%' },
  { title: '单价', dataIndex: 'Price', width: '10%' },
  //{ title: '金额', dataIndex: 'Amount', width: '10%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } },
]

var fromId = ''
var departmentId = ''
var requestDepartmentId = ''
var accountId = ''
var serviceItemIds = []
var requestId = ''
var state = 0
var enable = true

import RequestUser from './RequestUser'
import DeliveryUser from './DeliveryUser'
import ServiceItem from './ServiceItem'
import ShowDetail from './ShowDetail'
import EditServiceItem from './EditServiceItem'
import { constants } from 'crypto'
import { message } from 'ant-design-vue'

export default {
  components: {
    RequestUser,
    DeliveryUser,
    ServiceItem,
    ShowDetail,
    EditServiceItem,
  },
  props: {
    parentObj: Object,
  },
  data() {
    return {
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
      visible: false,
      pagination: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
      },
      loading: false,
      entity: {},
      rules: {},
      title: '',
      RequestUsersColumns,
      RequestUsersSelectedRowKeys: [],
      DeliveryUsersColumns,
      DeliveryUsersSelectedRowKeys: [],
      ServiceItemsColumns,
      ServiceItemsSelectedRowKeys: [],
      DepartmentDeliveryIdTreeData: [],
      DepartmentRequestIdTreeData: [],
      AccountIdData: [],
      DepartmentHead: [],
      rules: {
        RequestDepartmentId: [{ required: true, message: '必填' }],
        RequestUsers: [{ required: true, message: '必填' }],
        DeliveryDepartmentId: [{ required: true, message: '必填' }],
        DeliveryUsers: [{ required: true, message: '必填' }],
        AccountId: [{ required: true, message: '必填' }],
        ServiceItems: [{ required: true, message: '必填' }],
      },
      isAccount: false,
    }
  },
  methods: {
    init() {
      fromId = ''
      departmentId = ''
      serviceItemIds = []
      requestId = ''
      this.isAccount = false
      this.visible = true
      this.entity = {}
      this.entity.State = 0
      this.entity.ServiceItems = []
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.$http.post('/Base_Manage/Base_Department/GetTreeDataList', {}).then((resJson) => {
        if (resJson.Success) {
          let list = resJson.Data
          this.DepartmentDeliveryIdTreeData = list
          this.DepartmentRequestIdTreeData = list
        }
      })
      this.$http.post('/GBT_Base_Manage/GBT_Base_Account/GetDataList', {}).then((resJson) => {
        if (resJson.Success) {
          console.log(resJson)
          this.AccountIdData = resJson.Data
        }
      })
    },
    getApproverList(id, requestId, state) {
      this.$http
        .post('/GBT_Manage/GBT_ServiceRequest/GetApprovalList', { id: id, requestId: requestId, state: state })
        .then((resJson) => {
          if (resJson.Success) {
            console.log(resJson)
            this.DepartmentHead = resJson.Data
          } else {
            this.$message.error(resJson.Msg)
          }
        })
    },
    getTheData(id) {
      this.loading = true
      this.$http.post('/GBT_Manage/GBT_ServiceRequest/GetTheData', { id: id }).then((resJson) => {
        console.log('单据信息', resJson)
        this.loading = false
        if (resJson.Success) {
          let data = resJson.Data
          let RequestDepartmentId = JSON.parse(data.RequestDepartmentId)
          let DeliveryDepartmentId = JSON.parse(data.DeliveryDepartmentId)
          data.RequestDepartmentId = RequestDepartmentId
          data.DeliveryDepartmentId = DeliveryDepartmentId
          this.entity = data
          departmentId = this.entity.DeliveryDepartmentId
          requestDepartmentId = this.entity.RequestDepartmentId
          state = this.entity.State
          // this.getApproverList(requestDepartmentId, fromId, state)
          requestId = this.entity.Id
          if (data.ServiceItems) {
            this.isAccount = true
            data.ServiceItems.forEach(t => {
              t.Amount = t.Quantity * t.Price
            })
          }
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    openForm(param, title) {
      this.init()
      console.log(param)
      let item = param.item
      enable = param.enable
      if (item) {
        fromId = item.Id
        this.getTheData(item.Id)
      }
    },
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        if (enable) {
          this.loading = true

          this.entity.RequestDepartmentId = JSON.stringify(this.entity.RequestDepartmentId)
          this.entity.DeliveryDepartmentId = JSON.stringify(this.entity.DeliveryDepartmentId)
          console.log('保存：', this.entity)
          this.$http.post('/GBT_Manage/GBT_ServiceRequest/SaveAllData', this.entity).then((resJson) => {
            this.loading = false

            if (resJson.Success) {
              this.$message.success('操作成功!')
              this.visible = false
              console.log('保存返回结果：', resJson)
              this.getTheData(fromId)
              this.parentObj.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        } else {
          this.visible = false
        }
      })
    },
    contains(array, obj) {
      var i = array.length
      while (i--) {
        if (array[i].UserId === obj) {
          return i
        } else if (array[i].ServiceItemId === obj) {
          return i
        }
      }
      return false
    },
    onTreeRequestDepartmentChange(ids) {
      console.log(JSON.stringify(ids))
      requestDepartmentId = ids
      if (ids) {
        this.loading = true
        // if (fromId) {
        //   this.getApproverList(ids, fromId, state)
        // }
        this.$http
          .post('/GBT_Manage/GBT_ServiceRequest/GetServiceRequestUserList', {
            departmentIds: ids,
            RequestId: requestId,
          })
          .then((resJson) => {
            console.log('获取服务请求人员：', this.entity.RequestUsers)
            this.loading = false
            this.entity.RequestUsers = resJson.Data
          })
      }
    },
    onRequestUsersSelectChange(selectedRowKeys) {
      this.RequestUsersSelectedRowKeys = selectedRowKeys
    },
    handleRequestUsersEdit(item) {
      item.State = this.entity.State
      this.$refs.requestUser.openForm(item)
    },
    handleRequestUsersDelete(ids, UserId) {
      console.log(ids)
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk() {
          if (UserId) {
            let list = thisObj.entity.RequestUsers
            list.splice(thisObj.contains(list, UserId), 1)
            thisObj.entity.RequestUsers = list
          }
        },
      })
    },
    onTreeDeliveryDepartmentChange(ids) {
      console.log(ids)
      departmentId = ids
      if (ids) {
        this.loading = true
        this.$http
          .post('/GBT_Manage/GBT_ServiceRequest/GetServiceDeliveryUserList', {
            departmentIds: ids,
            RequestId: requestId,
          })
          .then((resJson) => {
            console.log('获取提供服务人员：', resJson)
            this.loading = false
            this.entity.DeliveryUsers = resJson.Data
          })
      }
    },
    onDeliveryUsersSelectChange(selectedRowKeys) {
      this.DeliveryUsersSelectedRowKeys = selectedRowKeys
    },
    handleDeliveryUsersEdit(item) {
      this.$refs.deliveryUser.openForm(item)
    },
    handleDeliveryUsersDelete(ids, UserId) {
      console.log(ids)
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk() {
          if (UserId) {
            let list = thisObj.entity.DeliveryUsers
            list.splice(thisObj.contains(list, UserId), 1)
            thisObj.entity.DeliveryUsers = list
          }
        },
      })
    },
    hanldleServiceItemsAdd() {
      let verify = true
      if (!departmentId) {
        message.warning('请选择提供服务部门', 2, null)
        verify = false
      }
      if (!this.entity.AccountId) {
        message.warning('请选择科目', 2, null)
        verify = false
      }
      if (!verify) {
        return
      }
      let obj = {
        ids: departmentId,
        RequestId: requestId,
        AccountId: this.entity.AccountId,
        ServiceItems: this.entity.ServiceItems,
      }
      this.$refs.serviceItem.openForm(obj)
    },
    hasServiceItemsSelected() {
      return this.ServiceItemsSelectedRowKeys.length > 0
    },
    onServiceItemsSelectChange(selectedRowKeys) {
      this.ServiceItemsSelectedRowKeys = selectedRowKeys
    },
    showDetail(name, content) {
      let param = { Name: name, Content: content }
      this.$refs.showDetail.openForm(param)
    },
    handleQtyEdit(id) {
      this.$refs.editServiceItem.openForm(id)
    },
    handleServiceItemsDelete(ids) {
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk() {
          if (ids) {
            let list = thisObj.entity.ServiceItems
            list.splice(thisObj.contains(list, ids[0]), 1)
            thisObj.entity.ServiceItems = list
            if(!list){
              this.isAccount = false
            }
          }
        },
      })
    },
    getServiceItems(items) {
      serviceItemIds = items
      let data = this.entity
      items.forEach(t => {
        t.Amount = t.Quantity * t.Price
      })
      data.ServiceItems = items
      this.entity = data
      console.log('获取服务项目：', data)
      this.isAccount = true
    },
    serviceIetmsRefresh() {
      this.getServiceItems(serviceItemIds)
    },
  },
}
</script>
